
package cz.muni.fi.pa165.carparkweb.actionbeans;

import cz.muni.fi.pa165.carpark.TO.ServiceCheckTO;
import cz.muni.fi.pa165.carpark.TO.VehicleTO;
import cz.muni.fi.pa165.carpark.servicies.ServiceCheckService;
import cz.muni.fi.pa165.carpark.servicies.VehicleService;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;

/**
 *
 * @author xmarton1
 */
@UrlBinding("/servicecheck/{$event}/{servicecheck.id}")
public class ServiceCheckActionBean implements ActionBean{
    
    private ActionBeanContext context;
    private static final Logger log = LoggerFactory.getLogger(ServiceCheckActionBean.class);
    
    @SpringBean
    protected ServiceCheckService serviceCheckService;
    
    @SpringBean
    protected VehicleService vehicleService;
    
    @ValidateNestedProperties(value = {
            @Validate(on = {"cancelCheckFinal"}, field = "dateOfCheck", required = true, minlength=1),
            @Validate(on = {"create", "save"}, field = "checkInterval", required = true, minvalue=1000),
            @Validate(on = {"create", "save"}, field = "checkPurpose", required = true, minlength=3)
    })
    private ServiceCheckTO servicecheck;
    
    @ValidateNestedProperties(value = {
            @Validate(on = {"create"}, field = "id", required = true)
    })
    private VehicleTO vehicle;
    private int doneChecksFilter = -1;
    private int activeChecksFilter = -1;
    private String vehicleFilter = "-1";
    
    public int isDoneChecksFilter() {
        return doneChecksFilter;
    }

    public void setDoneChecksFilter(int doneChecksFilter) {
        this.doneChecksFilter = doneChecksFilter;
    }

    public int isActiveChecksFilter() {
        return activeChecksFilter;
    }

    public void setActiveChecksFilter(int activeChecksFilter) {
        this.activeChecksFilter = activeChecksFilter;
    }

    public String getVehicleFilter() {
        return vehicleFilter;
    }

    public void setVehicleFilter(String vehicleFilter) {
        this.vehicleFilter = vehicleFilter;
    }
    
    public Resolution getByFilter(){
        log.debug("Filter submit");
        log.debug("done{}",doneChecksFilter);
        log.debug("active{}",activeChecksFilter);
        Long id = Long.parseLong(this.context.getRequest().getParameter("vehicleFilter"));
        if(id != -1){
            this.vehicle = this.vehicleService.retrieve(id);
        }
        else{
            this.vehicle = null;
        }
      
        return new ForwardResolution("/WEB-INF/jsp/servicecheck.jsp");
    }
    
    private VehicleTO checkVehicle;
    
    
    public VehicleTO getCheckVehicle(){
        return this.checkVehicle;
    }
    public void setCheckVehicle(VehicleTO checkVehicle){
        this.checkVehicle = checkVehicle;
    }
    
    public VehicleService getVehicleService() {
        return vehicleService;
    }

    public void setVehicleService(VehicleService vehicleService) {
        this.vehicleService = vehicleService;
    }

    public VehicleTO getVehicle() {
        return vehicle;
    }

    public void setVehicle(VehicleTO vehicle) {
        this.vehicle = vehicle;
    }
    
    @DefaultHandler
    public Resolution all(){
        log.debug("all()");
        return new ForwardResolution("/WEB-INF/jsp/servicecheck.jsp");
    }
    
    
    public Resolution add(){
        log.debug("add servicecheck");    
        return new ForwardResolution("/WEB-INF/jsp/servicecheckCreate.jsp");
    }
    
    public Resolution create(){
        log.debug("create servicecheck={}",servicecheck);
        servicecheck.setCheckDone(false);
        servicecheck.setIsActive(false);
        servicecheck.setDateOfCheck(null);
       
        serviceCheckService.createCheck(servicecheck);
       
        this.vehicle = this.vehicleService.retrieve(this.vehicle.getId());
        log.debug(vehicle.toString());
        vehicle.addControlServiceCheck(servicecheck);
        
        this.vehicleService.update(vehicle);
        return new RedirectResolution(this.getClass(),"all");
    }
    
    public Resolution cancelCheck(){
        log.debug("cancel servicecheck={}",servicecheck);
        return new ForwardResolution("/WEB-INF/jsp/cancelCheckForm.jsp");
    }
    
    public Resolution cancelCheckFinal(){     
        log.debug("cancel({})",servicecheck); 
        serviceCheckService.cancelCheck(servicecheck);
        return new RedirectResolution(this.getClass(), "all");
    }
    
    public Resolution storno(){
        log.debug("storno create");
        return new RedirectResolution(this.getClass(),"all");
    }
    
    public Resolution delete(){
        log.debug("delete({})",servicecheck.getId()); 
        serviceCheckService.deleteCheck(servicecheck);        
        return new RedirectResolution(this.getClass(),"all");
    }
    
    @Before(stages= LifecycleStage.BindingAndValidation, on= {"edit","save","cancelCheck","cancelCheckFinal","delete"})
    public void loadServichCheck(){
        String id = context.getRequest().getParameter("servicecheck.id");
        if(id == null){
            return;
        }
        servicecheck = serviceCheckService.retrieveCheck(Long.parseLong(id));
    }
    
    public Resolution edit(){
        log.debug("edit servicecheck={}",servicecheck);
        return new ForwardResolution("/WEB-INF/jsp/servicecheckEdit.jsp");
    }
    
    public Resolution save(){
        log.debug("update({})",servicecheck);
        serviceCheckService.updateCheck(servicecheck);
        return new  RedirectResolution(this.getClass(),"all");
    }
    
    public List<ServiceCheckTO> getChecks(){
        List<ServiceCheckTO> result = new ArrayList<ServiceCheckTO>();
        // Vehicle filter
        if(vehicle != null){
            result.addAll(vehicle.getControlServiceCheck());
        }
        else{
            result = serviceCheckService.retrieveAllServiceChecks();
        }
        
        // Active filter
        List<ServiceCheckTO> result2 = new ArrayList<ServiceCheckTO>();
        if(activeChecksFilter != -1){
            boolean activeFilter = activeChecksFilter == 1;
            for(ServiceCheckTO s : result){
                if(s.isIsActive() == activeFilter){
                    result2.add(s);
                }
            }
        }
        else{ result2 = result;}
        // done filter
        List<ServiceCheckTO> result3 = new ArrayList<ServiceCheckTO>();
        if(doneChecksFilter != -1){
            boolean doneFilter = doneChecksFilter == 1;
            for(ServiceCheckTO s : result2){
                if(s.isCheckDone() == doneFilter){
                    result3.add(s);
                }
            }
        }
        else{ result3 = result2;}
        return result3;
    }

    @Override
    public void setContext(ActionBeanContext context) {
        this.context = context;
    }

    @Override
    public ActionBeanContext getContext() {
        return this.context;
    }

    public ServiceCheckService getServiceCheckService() {
        return serviceCheckService;
    }

    public void setServiceCheckService(ServiceCheckService serviceCheckService) {
        this.serviceCheckService = serviceCheckService;
    }

    public ServiceCheckTO getServicecheck() {
        return servicecheck;
    }

    public void setServicecheck(ServiceCheckTO servicecheck) {
        this.servicecheck = servicecheck;
        try{
            this.checkVehicle = serviceCheckService.findServiceCheckVehicle(servicecheck);
        }catch(DataAccessException ex){    // no result
            this.checkVehicle = null;
        }
    }
    
    public List<VehicleTO> getVehicles() {
        
        return this.vehicleService.retrieveAllVehicles();
    }

}
